﻿using adminTemplateApi.Data;
using adminTemplateApi.Model;
using adminTemplateApi.Model.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace adminTemplateApi.Controllers
{
    public class MenuController : BaseController<Menus, int>
    {
        public MenuController(DBContext context) : base(context)
        {
        }

        protected override int GetIdFromObj(Menus obj)
        {
            return obj.Id;
        }

        [HttpGet("{areaId:int}")]
        public async Task<ActionResult<IEnumerable<Menus>>> AllInArea(int areaId)
        {
            return await db.Menus.Where(x => x.ShowIn == areaId).ToListAsync();
        }

        [HttpGet("{areaId}")]
        public async Task<IEnumerable<MenusVm>> AllInAreaVm(int areaId)
        {
            var list = await db.Menus.Where(x => x.ShowIn == areaId).ToListAsync();
            var pageIds = list.Where(x=>x.IsDynamic.HasValue && x.IsDynamic.Value && x.DynamicPageId.HasValue).Select(x=>x.DynamicPageId.Value).ToList();
            var dynamicPagesList = await db.DynamicPages.Where(x=>pageIds.Contains(x.Id)).ToListAsync();
            return list.Select(x =>
            {
                var dynamicPageType = dynamicPagesList.FirstOrDefault(y => y.Id == x.DynamicPageId)?.PageType;
                return new MenusVm()
                {
                    Id = x.Id,
                    Pid = x.Pid,
                    MenuName = x.MenuName,
                    MenuLabel = x.MenuLabel,
                    Route = x.Route,
                    IsDynamic = x.IsDynamic,
                    DynamicPageId = x.DynamicPageId,
                    StaticComponent = x.StaticComponent,
                    DynamicPageType = dynamicPageType,
                    Enable = x.Enable,
                    ShowIn = x.ShowIn,
                    Sort = x.Sort,
                    IsLink = x.IsLink,
                    LinkUrl = x.LinkUrl,
                    Target = x.Target
                };
            });
        }
    }
}
